//
//  YMFEditOrderViewController.swift
//  FlyingPigeon
//
//  Created by yang on 2019/5/26.
//  Copyright © 2019年 a. All rights reserved.
//

import Foundation
import UIKit

class YMFEditOrderViewController: UIViewController {
    
    
    @IBOutlet weak var carImageView: UIImageView!
    @IBOutlet weak var carName: UILabel!
    @IBOutlet weak var price: UILabel!
    @IBOutlet weak var ruleText: UITextView!
    
    var begainDate: Date?
    var endDate: Date?
    @IBOutlet weak var beginTimeLabel: UILabel!
    @IBOutlet weak var endTimeLabel: UILabel!
    @IBOutlet weak var placeLabel: UILabel!
    
    @IBOutlet weak var name: UITextField!
    @IBOutlet weak var phone: UITextField!
    
    @IBOutlet weak var totalPrice: UILabel!
    @IBOutlet weak var commitButton: UIButton!
    
    var orderModel: YMFOrderModel?
    
    var totalPriceStr = ""
    
    var placeData = ["飞鸽车行（福锦路-段店）", "逸旅租车（天福三街店）", "飞鸽车行（总店）", "方便租车（机场路店）"]
    
    var model: YMFPriceModel!
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = orderModel == nil ? "确认订单" : "订单详情"
        
        ruleText.isEditable = false
        ruleText.isScrollEnabled = false
       
        
//        self.view.window.
        
        var begainTime = Date()
        var endTime = Date()
        
        if let orderModel = self.orderModel {
            begainTime = orderModel.begainDate ?? Date()
            endTime = orderModel.endDate ?? Date()
            
            name.isUserInteractionEnabled = false
            name.text = orderModel.userName
            
            phone.isUserInteractionEnabled = false
            phone.text = orderModel.userPhone
            
            totalPrice.text =  "￥ \(orderModel.totalPrice)"
            
            commitButton.isHidden = true
            
            let attrStr = NSMutableAttributedString(string: "￥" + orderModel.carPrice + "/天")
            attrStr.addAttributes([NSAttributedStringKey.foregroundColor : UIColor.red], range: NSRange(location: 1, length: orderModel.carPrice.count))
            price.attributedText = attrStr
            
            carName.text = orderModel.carName
            carImageView.image = UIImage(named: orderModel.carImage)
            
            placeLabel.text = orderModel.placeName
            
        } else {
            let attrStr = NSMutableAttributedString(string: "￥" + model.price + "/天")
            attrStr.addAttributes([NSAttributedStringKey.foregroundColor : UIColor.red], range: NSRange(location: 1, length: model.price.count))
            price.attributedText = attrStr
            
            if model.placeName != "" {
                placeLabel.text = model.placeName
                
            }
            
            carName.text = model.name
            carImageView.image = UIImage(named: model.headerImage)
            
            let tap1 = UITapGestureRecognizer(target: self, action: #selector(begainLabelTapAction(_:)))
            beginTimeLabel.addGestureRecognizer(tap1)
            
            let tap2 = UITapGestureRecognizer(target: self, action: #selector(endLabelTapAction(_:)))
            endTimeLabel.addGestureRecognizer(tap2)
        }
        
        let formatter = DateFormatter()
        formatter.dateFormat = "YYYY-MM-dd"
        let begainStr = formatter.string(from: begainTime)
        let endStr = formatter.string(from: endTime)
        beginTimeLabel.text = begainStr
        endTimeLabel.text = endStr
        begainDate = begainTime
        endDate = endTime
      
        
//        let tap3 = UITapGestureRecognizer(target: self, action: #selector(placeLabelTapAction(_:)))
//        placeLabel.addGestureRecognizer(tap3)
    
        
        
       
    }
    
    @objc func begainLabelTapAction(_ tap: UITapGestureRecognizer) {
        
       let datePick = DatePickerDialog()
        
        datePick.show("选择时间", datePickerMode: .date) { (date) in
            if date == nil {
                return
            }
            let formatter = DateFormatter()
            formatter.dateFormat = "YYYY-MM-dd"
           let begainStr = formatter.string(from: date!)
            self.beginTimeLabel.text = begainStr
            self.begainDate = date
            self.updateTotalPrice()
        }
    }
    
    
    @objc func endLabelTapAction(_ tap: UITapGestureRecognizer) {
        
        let datePick = DatePickerDialog()
        datePick.show("选择时间", datePickerMode: .date) { (date) in
            if date == nil {
                return
            }
            let formatter = DateFormatter()
            formatter.dateFormat = "YYYY-MM-dd"
            let str = formatter.string(from: date!)
            self.endTimeLabel.text = str
            self.endDate = date
            self.updateTotalPrice()
        }
    }
    
     @objc func placeLabelTapAction(_ tap: UITapGestureRecognizer) {
        
        
    }
    
    func updateTotalPrice() {
        if let begainTime = begainDate, let endTime = endDate {
           let interval = endTime.timeIntervalSince(begainTime)
            if interval > 0 {
                
                let dayNumber: NSInteger = NSInteger(interval / (60.0 * 60 * 24))
                
                let total = dayNumber * (model.price as NSString).integerValue
                totalPriceStr = "\(total)"
                totalPrice.text =  "￥ \(total).00"
            }
            
        }
        
    }
    
    @IBAction func commitAction(_ sender: Any) {
       
        
        let orderModel = YMFOrderModel()
        orderModel.carName = carName.text ?? ""
        orderModel.carPrice = model.price
        orderModel.userName = name.text ?? ""
        orderModel.userPhone = phone.text ?? ""
        orderModel.totalPrice = totalPriceStr
        orderModel.carImage = model.headerImage
        orderModel.begainDate = begainDate
        orderModel.endDate = endDate
        orderModel.orderCode = "\(CUnsignedLongLong(arc4random_uniform(899999999) + 100000000))"
        
        var orderInfo = YMFOrderInfoManager.share().getData()
        orderInfo.append(orderModel)
        YMFOrderInfoManager.share().saveData(orderInfo: orderInfo)
        
        navigationController?.popToRootViewController(animated: true)
        
    }
}


extension YMFEditOrderViewController: UIPickerViewDataSource, UIPickerViewDelegate {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return placeData.count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return placeData[row]
    }
    
    
    func view(forRow row: Int, forComponent component: Int) -> UIView? {
        let label = UILabel()
        label.text = placeData[row]
        label.sizeToFit()
        return label
    }
    
  
    
}
